package cn.elead.it.sso.server.controller;

import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.gitee.elead.api.ApiAssert;
import com.gitee.elead.api.emuns.ErrorCodeEnum;
import com.gitee.elead.web.api.ApiResponses;
import com.gitee.elead.web.controller.SuperController;

import cn.elead.it.sso.core.login.SsoTokenLoginHelper;
import cn.elead.it.sso.core.model.SsoUser;
import cn.elead.it.sso.core.store.SsoLoginStore;
import cn.elead.it.sso.core.store.SsoSessionIdHelper;
import cn.elead.it.sso.system.emuns.UserStatusEnum;
import cn.elead.it.sso.system.model.User;
import cn.elead.it.sso.system.service.IUserService;
import cn.hutool.core.util.IdUtil;

/**
 * App单点登录
 * 
 * @author luopeng
 *
 */
@RestController
@RequestMapping("/app")
public class AppController extends SuperController {

	@Autowired
	private IUserService userService;

	/**
	 * Login
	 *
	 * @param username
	 * @param password
	 * @return
	 */
	@PostMapping("/login")
	public ApiResponses<String> login(String username, String password) {

		// valid login
		User user = userService.findUser(username);
		// 用户不存在
		ApiAssert.notNull(ErrorCodeEnum.USERNAME_OR_PASSWORD_IS_WRONG, user);
		// 用户名密码错误
		ApiAssert.isTrue(ErrorCodeEnum.USERNAME_OR_PASSWORD_IS_WRONG, Md5Crypt.apr1Crypt(password, user.getUserId()).equals(user.getPassword()));
		// 用户被禁用
		ApiAssert.isTrue(ErrorCodeEnum.USER_IS_DISABLED, UserStatusEnum.DISABLE.equals(user.getStatus()));

		// 1、make sso user
		SsoUser ssoUser = new SsoUser();
		ssoUser.setUserId(user.getUserId());
		ssoUser.setUserName(user.getUserName());
		ssoUser.setVersion(IdUtil.simpleUUID());
		ssoUser.setExpireMinite(SsoLoginStore.getRedisExpireMinite());
		ssoUser.setExpireFreshTime(System.currentTimeMillis());

		// 2、generate sessionId + storeKey
		String sessionId = SsoSessionIdHelper.makeSessionId(ssoUser);

		// 3、login, store storeKey
		SsoTokenLoginHelper.login(sessionId, ssoUser);

		// 4、return sessionId
		return success(sessionId);
	}

	/**
	 * Logout
	 *
	 * @param sessionId
	 * @return
	 */
	@RequestMapping("/logout")
	@ResponseBody
	public ApiResponses<String> logout(String sessionId) {
		// logout, remove storeKey
		SsoTokenLoginHelper.logout(sessionId);
		return success(sessionId);
	}

	/**
	 * logincheck
	 *
	 * @param sessionId
	 * @return
	 */
	@RequestMapping("/logincheck")
	@ResponseBody
	public ApiResponses<SsoUser> logincheck(String sessionId) {
		// logout
		SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(sessionId);

		ApiAssert.notNull(ErrorCodeEnum.UNAUTHORIZED, ssoUser);

		return success(ssoUser);
	}

}